import pandas as pd
import numpy as np

# 读取CSV数据
df = pd.read_csv('../PointDownLoad/A6顶板底钢筋网_分裂坐标.csv')

# 提取所有以 x, y, z 开头的列
x_columns = [col for col in df.columns if col.startswith('x')]
y_columns = [col for col in df.columns if col.startswith('y')]
z_columns = [col for col in df.columns if col.startswith('z')]

# 计算最小值
x_min = int(df[x_columns].min().min())
y_min = int(df[y_columns].min().min())
z_min = int(df[z_columns].min().min())

# 对所有以 x 开头的列的值减去 x_min
df[x_columns] = df[x_columns] - x_min

# 对所有以 y 开头的列的值减去 y_min
df[y_columns] = df[y_columns] - y_min

# 对所有以 z 开头的列的值减去 z_min
df[z_columns] = df[z_columns] - z_min


# 计算长度的函数
def calculate_length(row):
    # 提取坐标，形成元组列表
    coordinates = []
    for i in range(1, len(x_columns) + 1):
        if not pd.isna(row[f'x{i}']):
            coordinates.append((row[f'x{i}'], row[f'y{i}'], row[f'z{i}']))

    # 计算连续点之间的距离
    total_length = 0
    for i in range(len(coordinates) - 1):
        point1 = coordinates[i]
        point2 = coordinates[i + 1]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance

    if row['Start Angle'] != 0:
        point1 = coordinates[1]
        point2 = coordinates[2]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length -= distance

    if row['End Angle'] != 0:
        point1 = coordinates[len(x_columns) - 3]
        point2 = coordinates[len(x_columns) - 2]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length -= distance

    return total_length


# 应用函数计算每根钢筋的长度
df['Length'] = df.apply(calculate_length, axis=1)

# 设置阈值  判断横筋纵筋
threshold = df['Length'].mean()

# Classify as 横筋(1) or 纵筋(0)
df['Type'] = df['Length'].apply(lambda x: '0' if x >= threshold else '1')

# # 删除 Length 列
# df.drop(columns=['Length'], inplace=True)

df.to_csv("../PointDownLoad/A6顶板底钢筋网_相对坐标系.csv", index=False)
